package 数据结构.循环链表;

//循环链表实现
public class CycleListNode<T> {

    private Node head;
    private int size = 0;

    public class Node{
        T data;
        Node next;

        public Node(T data){
            this.data = data;
            next = null;
        }

    }

    public boolean add(T data) {//添加节点
        boolean isSuccessful=false;
        if(head==null){//处理空表
            Node node = new Node(data);
            head=node;
            node.next=head;
            isSuccessful=true;
        }else{//不为空时
            Node node= head;
            while(true){
                if (node.next==head){
                    break;
                }
                node=node.next;
            }
            Node newNode = new Node(data);
            node.next=newNode;
            newNode.next=head;
            isSuccessful=true;

        }
        return isSuccessful;

    }

    public Node delete(int index) {//删除制定节点
        Node outputNode = null;
        Node node= head; //指向第一个节点
        if ((index)==0) {//查到该节点的前一个节点
            outputNode = node;
            head=null;
            head = node.next;//删除语句
            return outputNode;
        }
        int location=0;//计时器
        while (true){  //
            if (isEmpty()) {//如果链表为空中断
                break;
            }else  if (location==index-1){//查到该节点的前一个节点
                outputNode=node.next;
                node.next=node.next.next;//删除语句

                break;
            }
            if (node.next==null){
                break;
            }
            location++;//计时器加加
            node=node.next;//节点后移
        }
        return outputNode;

    }

    public void display() {//遍历整个链表

        Node node = head;
        while (node != null) {
            System.out.println(node.data.toString());

            if (node.next == head) {
                break;
            }
            node = node.next;

        }
    }

    public boolean isEmpty() {
        return head==null;
    }

    public static void main(String[] args) {
        CycleListNode cycleListNode = new CycleListNode();
        cycleListNode.add(1);
        cycleListNode.add(2);
        cycleListNode.add(3);
        cycleListNode.add(4);
        cycleListNode.add(5);

        cycleListNode.display();
    }

}


